<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="担保客户查询"
          clearable
          @change="getData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <c-select
          placeholder="客户类型"
          clearable
          @change="getData()"
          v-model="params.org_class"
          :options="enumCustomerType"
        ></c-select>
      </el-form-item>
      <el-form-item v-if="isCity">
        <select-address
          v-model="params.address_code"
          auto-top
          :bottom-level="2"
          placeholder="地址查询"
          clearable
          @change="getData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <select-date-cascader
          placeholder="放款时间"
          class="form-control-ml"
          v-model="queryDate"
          @select="handleDateQuery"
        ></select-date-cascader>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="enumReviewApprovalSelect"
          clearable
          @change="getData()"
          placeholder="项目状态"
          v-model="params['review_approval.in']"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-upload2" @click="showImport">导入</el-button>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('十二大产业贷')"
        >
          导出
        </el-button>
      </el-form-item>
    </el-form>

    <c-table
      border
      v-loading="loading"
      ref="table"
      class="table-sm"
      :columns="tableColumns"
      @sort-change="handleSortChange"
      :data="tableData"
    >
      <template v-slot:use="scope">
        <div class="text-truncate" :title="scope.row.funds_use_dir">
          {{ scope.row.funds_use_dir }}
        </div>
      </template>
      <template v-slot:status="scope">
        <div class="status-label" :class="`badge-${scope.row.statusStyle}`">
          {{ scope.row.statusLabel }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="tableCount"
        @current-change="getData"
      ></el-pagination>
    </div>

    <project-new-dialog
      :visible.sync="applyVisible"
      :table-id="tableId"
      :form-data="applyRow"
      @success="getData()"
    ></project-new-dialog>

    <import-excel
      :excel-template="importFileUrl"
      title="导入项目信息"
      :tip="false"
      :post-api="postUrl"
      :visible.sync="importVisible"
      @success="handleImportSuccess"
    ></import-excel>

    <project-view-dialog
      :visible.sync="visible"
      :batch-no="attachNo"
      :query-id="queryId"
    ></project-view-dialog>

    <import-tip :visible.sync="tipVisible" @success="getData()" :batch-no="batchNo"></import-tip>

    <attach-dialog :visible.sync="attachVisible" :project-data="attachProjectData"></attach-dialog>
  </div>
</template>
<script>
import { queryTrouble } from '@vimi/utils-api'
import {
  baseTableColumns,
  dataAdapter,
  enumCustomerType,
  enumReviewApproval,
  enumReviewStyle,
  parseCascaderDate,
  enumReplaceStatus,
  enumReplaceStatusStyle,
  enumReviewApprovalSelect,
} from '@/bank/views/limit/index'

import ProjectViewDialog from '@/bank/views/limit/ProjectViewDialog'
import hndTableMixin from '@/bank/views/limit/mixins'
import SelectAddress from '@/components/select/SelectAddress'
import ProjectNewDialog from '@/bank/views/limit/ProjectNewDialog'
import ImportExcel from '@/components/ImportExcel'
import ImportTip from '@/bank/views/limit/import/ImportTip'
import AttachDialog from '@/bank/views/limit/AttachDialog'
import SelectDateCascader from '@/components/select/SelectDateCascader'

export default {
  components: {
    ProjectViewDialog,
    SelectAddress,
    ProjectNewDialog,
    ImportExcel,
    ImportTip,
    AttachDialog,
    SelectDateCascader,
  },
  mixins: [hndTableMixin],
  props: {},
  data() {
    return {
      enumCustomerType,
      enumReviewApprovalSelect,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
      },
      queryDate: [],
      order: {
        create_time: 'desc',
      },
      tableName: 'datum_one_county_industry',
      tableColumns: [
        ...baseTableColumns,
        {
          attrs: {
            label: '项目状态',
            prop: 'statusLabel',
            align: 'center',
            sortable: 'review_approval',
            width: '110px',
          },
          render: (h, { row }) =>
            h('div', { style: { lineHeight: 1.2 } }, [
              h('div', { class: `text-${row.statusStyle}` }, row.statusLabel),
              h('small', { class: `text-${row.replaceStatusStyle}` }, row.replaceStatus),
            ]),
        },
        {
          attrs: { label: '操作', align: 'center', width: '160px' },
          operations: [
            {
              content: '修改',
              icon: 'fa fa-edit',
              event: this.handleToEdit,
              ifRender: row => +row.review_approval === 0 && row.bank_id === this.clientId,
            },
            {
              content: '删除',
              icon: 'fa fa-trash',
              attrs: { class: 'text-danger py-0 px-2' },
              event: this.handleDelete,
              ifRender: row => +row.review_approval === 0 && row.bank_id === this.clientId,
            },
            { content: '上传', icon: 'fa fa-clipboard', event: this.handleUpload },
            { content: '查看', icon: 'fa fa-search', event: this.showCreditFile },
          ],
        },
      ],

      queryId: '',
      attachNo: '',
      visible: false,

      // 编辑
      applyVisible: false,
      applyRow: {},
      tableId: '',

      importVisible: false,

      tipVisible: false,
      batchNo: '',

      attachProjectData: {},
      attachVisible: false,
    }
  },
  computed: {
    isCity() {
      return +this.user.orgRegionLever < 3
    },
    bankName() {
      return this.org.orgName || '-'
    },
    bankCode() {
      return this.org.orgCode
    },
    bankType() {
      return this.user.clientOrgClassType
    },
    postUrl() {
      return (
        '/api/credit/import/' +
        queryTrouble(this.tableName, {
          importKey: 'datum_one_county_industry_template_bank_ep',
          'bank_name.eq': this.bankName,
          'bank_id.eq': this.clientId,
          'bank_code.eq': this.bankCode,
          'bank_type.eq': this.bankType,
        })
      )
    },
    importFileUrl() {
      return `//vimi8.oss-cn-shenzhen.aliyuncs.com/template/黔农十二贷导入模板.xlsx?${+new Date()}`
    },
  },
  watch: {},
  created() {
    this.getData()
  },
  mounted() {},
  methods: {
    handleSortChange({ order, column }) {
      if (!order) {
        this.order = { create_time: 'desc' }
      } else {
        this.order = {}
        this.order[column.sortable] = order.includes('asc') ? 'asc' : 'desc'
      }
      this.getData()
    },
    handleUpload(row = {}) {
      this.attachProjectData = row
      this.attachVisible = true
    },
    handleImportSuccess(data) {
      this.tipVisible = true
      this.importVisible = false
      this.batchNo = data
    },
    dataAdapter(item) {
      dataAdapter(item)
      item.statusLabel = enumReviewApproval[item.review_approval]
      item.statusStyle = enumReviewStyle[item.review_approval]
      item.replaceStatus = enumReplaceStatus[item.is_replace] || ''
      item.replaceStatusStyle = enumReplaceStatusStyle[item.is_replace]
      return item
    },
    showImport() {
      this.importVisible = true
    },
    handleDateQuery(val) {
      const [start, end] = parseCascaderDate(val)
      this.params['create_time.gte'] = start
      this.params['create_time.lte'] = end
      this.getData()
    },

    handleDelete(row = {}) {
      this.$utils
        .msgbox({
          message: `确定删除客户${row.customer_name}?`,
          beforeClose: () =>
            this.$api.deleteData(this.$serviceName, this.tableName, row.customer_related_id),
        })
        .then(() => {
          this.getData()
          this.$message.success('删除成功！')
        })
        .catch(() => this.$message.error('删除失败，请重试！'))
    },
    showCreditFile(row = {}) {
      this.queryId = row.customer_related_id
      this.attachNo = row.project_approval_batch_bank_id || ''
      this.visible = true
    },
    handleToEdit(row = {}) {
      this.applyRow = { ...row }
      this.tableId = this.applyRow['customer_related_id'] || ''
      this.applyVisible = true
    },
  },
}
</script>
<style lang="scss" scoped>
.status-label {
  display: inline-block;
  padding: 0.25em 0.4em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  text-align: center;
  vertical-align: baseline;
  border-radius: 0.25rem;
  transition: color 0.15s;
}
</style>
